package social;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SocialDBC db = (SocialDBC) getServletContext().getAttribute("database");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		HttpSession session = request.getSession();
		
		//System.out.println("Logging in.");
		boolean login = db.checkPassword(username, password);
		if (login==false) {
			//bad password or username
			//System.out.println("Bad login.");
			session.setAttribute("login", "false");
			request.getRequestDispatcher("homepage.jsp").forward(request, response);
		} else {
			//login
			session.setAttribute("username", username);
			session.setAttribute("friendList", db.getFriendList(username));
			session.setAttribute("login", "true");
			//request.setAttribute("profileName", username);
			session.setAttribute("profileName", username);
			//request.getA
			response.setHeader("Cache-Control","no-cache, no-store, must-revlaidate"); 
			response.setDateHeader("Expires", -1); //Causes the proxy cache to see the page as "stale"
			response.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility
			//TODO quizHistory
			//TODO acheivements
			request.getRequestDispatcher("user-profile.jsp").forward(request, response);
		}
	}

}
